import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;

import productidentification.IProductIdentifier;

public class AmazonProductIdentifier implements IProductIdentifier
{
  /*
   * Your AWS Access Key ID, as taken from the AWS Your Account page.
   */
  private static final String AWS_ACCESS_KEY_ID = "AKIAJC3UF5U56NQPVT7A";

  /*
   * Your AWS Secret Key corresponding to the above ID, as taken from the AWS
   * Your Account page.
   */
  private static final String AWS_SECRET_KEY    = "gY01uAozf4aEJ9tHaoLXNUlvpiSKUOVYhtzCNBca";
  private static final String ENDPOINT          = "ecs.amazonaws.com";

  @Override
  public String identifyProduct(String barcode) throws Exception
  {
    /*
     * Set up the signed requests helper 
     */
    SignedRequestsHelper helper;
    try
    {
      helper = SignedRequestsHelper.getInstance(ENDPOINT, AWS_ACCESS_KEY_ID, AWS_SECRET_KEY);
    }
    catch (Exception e)
    {
      e.printStackTrace();
      return "";
    }

    String requestUrl = null;
    String title = null;

    Map<String, String> params = new HashMap<String, String>();
    params.put("Service", "AWSECommerceService");
    params.put("Version", "2009-03-31");
    params.put("Operation", "ItemSearch");
    params.put("AssociateTag", "aztag-20");
    params.put("SearchIndex", "All");
    params.put("Keywords", barcode);
    params.put("ResponseGroup", "Small");

    requestUrl = helper.sign(params);
    // System.out.println("Signed Request is \"" + requestUrl + "\"");

    title = fetchTitle(requestUrl);
    return title;
  }

  /*
   * Utility function to fetch the response from the service and extract the
   * title from the XML.
   */
  private static String fetchTitle(String requestUrl)
  {
    String title = null;
    try
    {
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();
      Document doc = db.parse(requestUrl);
      Node titleNode = doc.getElementsByTagName("Title").item(0);
      title = titleNode.getTextContent();
    }
    catch (Exception e)
    {}
    return title;
  }

  @Override
  public String getName()
  {
    return "Amazon Product Identifier Plugin";
  }

  @Override
  public String getDescription()
  {
    return "Uses the Amazon Product Advertising API to identify a product given its UPC barcode.";
  }

  public static void main(String[] args)
  {
    try
    {
      String barcode = "895035002019";

      AmazonProductIdentifier identifier = new AmazonProductIdentifier();
      String result = identifier.identifyProduct(barcode);
      System.out.println("Identifying product \"" + barcode + "\" yielded: '" + result + "'");
    }
    catch (Exception e)
    {
      System.err.print("Identifying product failed! Error: ");
      if (e.getMessage() != null)
        System.err.println(e.getMessage());
      e.printStackTrace();
    }
  }

}
